import * as Sequelize from "sequelize";
import { Application } from "egg";

interface OrgUserAttributes {
  id: string;
  org_id: string;
  user_id: string;
  create_user_id: string;
  modify_user_id: string;
  create_time: string;
  modify_time: string;
}

type OrgUserInstance = Sequelize.Instance<OrgUserAttributes> &
  OrgUserAttributes;

export default (app: Application) => {
  const { UUID, UUIDV4, DATE, NOW } = app.Sequelize;
  const attributes: SequelizeAttributes<OrgUserAttributes> = {
    id: {
      type: UUID,
      primaryKey: true,
      allowNull: false,
      defaultValue: UUIDV4
    },
    org_id: { type: UUID, primaryKey: true, allowNull: false },
    user_id: { type: UUID, primaryKey: true, allowNull: false },
    create_user_id: { type: UUID, allowNull: false },
    modify_user_id: { type: UUID, allowNull: false },
    create_time: { type: DATE, allowNull: false, defaultValue: NOW },
    modify_time: { type: DATE, allowNull: false, defaultValue: NOW }
  };
  const model = app.model.define<OrgUserInstance, OrgUserAttributes>(
    "OrgUser",
    attributes,
    {
      tableName: "t_org_users"
    }
  );
  model.associate = () => {
    app.model.models.OrgUser.belongsTo(app.model.models.Org, {
      foreignKey: "org_id",
      targetKey: "id"
    });
    app.model.models.OrgUser.belongsTo(app.model.models.User, {
      foreignKey: "user_id",
      targetKey: "id"
    });
  };
  return model;
};
